import CryptoJS from "crypto-js";

const DEFAULT_KEY = '18175511196cba89'
const DEFAULT_IV = 'abc6911155718189'

export default {
  /**
   * 加密
   * @param word
   * @param keyStr
   * @returns {string}
   */
  aesEncrypt(word, keyStr) {
    // 16位的密钥，自己定义，和下面的解密密钥要相同
    keyStr = keyStr || DEFAULT_KEY
    //字符串到数组转换，解析密钥
    var key = CryptoJS.enc.Utf8.parse(keyStr)
    var srcs = CryptoJS.enc.Utf8.parse(word)
    var iv = CryptoJS.enc.Utf8.parse(DEFAULT_IV)
    
    //mode:加密万式; padding:填充方式; iv:偏移向量(可选)
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
      iv: iv,
    })
    //console.log('加密后数据', CryptoJS.enc.Hex.stringify(encrypted.ciphertext))
    return CryptoJS.enc.Hex.stringify(encrypted.ciphertext)
  },
  
  /**
   * 解密
   * @param word
   * @param keyStr
   * @returns {string}
   */
  aesDecrypt(word, keyStr) {
    keyStr = keyStr || DEFAULT_KEY
    var key = CryptoJS.enc.Utf8.parse(keyStr)
    var iv =  CryptoJS.enc.Utf8.parse(DEFAULT_IV)
    
    var decrypted = CryptoJS.AES.decrypt(word, key, {
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
      iv: iv,
    })
    return decrypted.toString()
  },
}
